package com.kpx.app.view;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.kpx.app.R;
import com.kpx.app.activity.ActivityTaskDetail;
import com.kpx.app.adapter.TaskAdapter;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.TaskBean;
import com.kpx.app.configs.Constants;
import com.kpx.app.fragment.FragmentMyTask;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/2/26.
 */

public class ViewTaskYugao extends LinearLayout {
    @BindView(R.id.lv_task_show)
    ListView lvTaskShow;
    @BindView(R.id.custom_view)
    XRefreshView outView;
    @BindView(R.id.txt_empty_mention)
    TextView txtEmptyMention;
    @BindView(R.id.txt_mention_time)
    TextView txtMentionTime;
    @BindView(R.id.btn_cancel_mention)
    Button btnCancelMention;
    private Context context;
    private boolean isRefresh;
    private int pageNow;
    private List<TaskBean> taskBeans = new ArrayList<>();
    private double totalPage;
    private TaskAdapter adapter;
    private double pageSize;
    private FragmentMyTask fragmentMyTask;
    private boolean doChange = true;
    private boolean isreQuesting = false;

    public ViewTaskYugao(Context context, FragmentMyTask fragmentMyTask) {
        super(context);
        this.fragmentMyTask = fragmentMyTask;
        initView(context);
    }

    public ViewTaskYugao(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ViewTaskYugao(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(final Context context) {
        this.context = context;
        View view = View.inflate(context, R.layout.view_task_yugao, this);
        ButterKnife.bind(view);
        initRefreshView();
        setData(context);
        handler.sendEmptyMessageDelayed(0, 1000);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (doChange && taskBeans != null && taskBeans.size() > 0) {
                adapter.notifyDataSetChanged();
            }
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    };

    /**
     * 设置数据
     *
     * @param context
     */
    private void setData(final Context context) {
        //商品列表的上下拉刷新操作
        outView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                pageNow = 1;
                getTasks();// 获取数据
            }

            @Override
            public void onLoadMore(boolean isSlience) {
                isRefresh = false;
                if (pageNow >= totalPage) {
                    ToastUtil.getInstance().showToast(context, "没有更多了");
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            outView.stopLoadMore();
                        }
                    }, 600);
                } else {
                    pageNow++;
                    getTasks();// 获取数据
                }
            }
        });
        adapter = new TaskAdapter(context, taskBeans, R.layout.item_task_main_show, fragmentMyTask, 1);
        lvTaskShow.setAdapter(adapter);
        lvTaskShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.KEY_TASK_BEAN, taskBeans.get(position));
                ActivityTaskDetail.intype = ActivityTaskDetail.YUGAO_TYPE_IN;
                IntentUtil.gotoActivity(context, ActivityTaskDetail.class, bundle);
            }
        });
        isRefresh = true;
        getTasks();
    }

    private void getTasks() {
        if (isreQuesting) {
            return;
        }
        isreQuesting = true;
        ((ActivityBase) context).showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("pageIndex", pageNow + "");
        map.put("pageSize", "20");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                isreQuesting = false;
                ((ActivityBase) context).dissmissLoadingDialog();
                if (isRefresh) {
                    outView.stopRefresh();
                } else {
                    outView.stopLoadMore();
                }
                if (result.getCode() == 0) {
                    ArrayList<TaskBean> getData = (ArrayList<TaskBean>) result.getData();
                    if (isRefresh) {
                        taskBeans.clear();

                    } else {
                        if (getData.size() % pageSize != 0) {
                        }
                    }
                    totalPage = result.getPage().getPageSize();
                    outView.setAutoLoadMore(true);
                    outView.setPullRefreshEnable(true);
                    outView.setPullLoadEnable(true);
                    taskBeans.addAll(getData);
                    adapter.setData(taskBeans);
                    if (taskBeans.size() == 0) {
                        txtEmptyMention.setText("暂无相关任务信息");
                        txtEmptyMention.setOnClickListener(null);
                        txtEmptyMention.setVisibility(View.VISIBLE);
                    } else {
                        txtEmptyMention.setVisibility(View.GONE);
                    }
                } else {
                    ToastUtil.getInstance().showToast(context, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                isreQuesting = false;
                ((ActivityBase) context).dissmissLoadingDialog();
                if (isRefresh&&taskBeans.size() == 0) {
                    outView.stopRefresh();
                    txtEmptyMention.setText("获取信息失败，点击重试");
                    txtEmptyMention.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            getTasks();// 获取数据
                        }
                    });
                } else {
                    outView.stopLoadMore();
                }
                ToastUtil.getInstance().showToast(context, error);
            }

        }, TaskBean.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_GET_TASK_YUGAO, true, map);

    }


    /**
     * 初始化上下拉刷新
     */
    private void initRefreshView() {
        outView.setPullLoadEnable(true);
        outView.setPinnedTime(1000);
        outView.setAutoLoadMore(true);
//		outView.setCustomHeaderView(new CustomHeader(this));
//		outView.setCustomHeaderView(new XRefreshViewHeader(this));
        outView.setMoveForHorizontal(true);
//        outView.setCustomFooterView(new CustomerFooter(this));
//		outView.setPinnedContent(true);
        /**
         *scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
         *SCROLL_STATE_IDLE是当屏幕停止滚动时
         *SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时（The user is scrolling using touch, and their finger is still on the screen）
         *SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时（The user had previously been scrolling using touch and had performed a fling）
         */
        outView.setOnAbsListViewScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState){
                    case SCROLL_STATE_IDLE:
                        doChange = true;
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                    case SCROLL_STATE_FLING:
                        doChange = false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    @OnClick(R.id.btn_cancel_mention)
    public void onClick() {
    }

    public void refreshData() {
        isRefresh = true;
        pageNow = 1;
        getTasks();// 获取数据
    }
}
